<?php
namespace app\bancard\controller;

use app\common\lib\Broker;
use think\Controller;
use think\facade\Cache;
use app\common\lib\Dir;
use app\common\lib\Curl;
use GuzzleHttp\Client;

class Common extends Controller
{
    protected $config;
    protected $soo_broker;
    protected $schooInfo;
    protected $access_token;
    protected $subject;
    protected $devices;

    //构造函数
    public function __construct()
    {
        $this->soo_broker = new Broker(config('app.sso.sso_server'), config('app.sso.sso_broker_id'), config('app.sso.sso_broker_secret'));
        $this->sso_login();
        $this->access_token = $this->soo_broker->getAccessToken();
        $this->schooInfo = $this->getSchool();
        $this->subject = $this->allSubject();

        $data = [
            [
                'id' => 1,
                'value' => 3600
            ]
        ];
        Cache::set('config_set', $data, 0);
        parent::__construct();
        $this->assign('schooInfo', $this->schooInfo['data']);
        $this->assign('subject', json_encode($this->subject, true));
    }

    //初始化
    protected function initialize()
    {
        $isLogin = $this->isLogin();
        if (!$isLogin) {
            echo "<script>window.top.location = 'https://mp.uxuj.cn/admin/index/login'</script>";die;
            exit();
        }
    }

    //设置学校
    public function setschool()
    {
        $data = request()->param();
        session('schoolInfo', $this->schooInfo['data'][$data['index']]);
        return show(1, "设置成功", 0, 200);
    }

    //得到学校
    public function getSchool()
    {
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/school/index", ['access_token' => $this->access_token]);
        $d = json_decode($c, true);

        if (!empty($d['data'])) {
            $schoolInfo = session('schoolInfo');
            if (!$schoolInfo || !in_array($schoolInfo['id'], array_column($d['data'], 'id'))) {
                session('schoolInfo', $d['data'][0]);
            }
        } else {
            session('schoolInfo', null);
        }

        return $d;
    }

    /**
     *
     * 得到指定学校年级信息
     * @apiName getGrade
     * @apiGroup Comme
     *
     * @apiParam {string} access_token
     *
     * @apiSuccess {String[]} data 取得的年级信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　  [code] => 1
     * [msg] =>
     * [time] => 1573529107
     * [data] => Array
     * (
     * [0] => Array
     * (
     * [id] => 1
     * [name] => 一年级
     * [stage] => 1
     * [key] => 1
     * )
     *
     * [1] => Array
     * (
     * [id] => 2
     * [name] => 二年级
     * [stage] => 1
     * [key] => 2
     * )
     *
     * )
     * ]
     */
    public function getGrade()
    {

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/grade", ['access_token' => $this->access_token]);
        $d = json_decode($c, true);

        return $d;
    }

    /**
     *
     * 得到指定ID数组的教师信息
     * @apiName getTeacher
     * @apiGroup Comme
     *
     * @apiParam {string[]} $ids teacher_id组成的数字数组
     *
     * @apiSuccess {String[]} data 取得的教师信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　  [code] => 1
     * [msg] =>
     * [time] => 1573529107
     * [data] => Array
     * (
     * [34] => Array
     * (
     * [id] => 34
     * [name] => 甄子涵
     * [mobile] => 18911621396
     * )
     *
     * [35] => Array
     * (
     * [id] => 35
     * [name] => 樊聪燕
     * [mobile] => 17600136775
     * )
     *
     * )
     * ]
     */
    public function getTeacher($ids = [])
    {
        if (empty($ids) || !is_array($ids))
            return ['data'=>[]];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/teacher/profile", ['access_token' => $this->access_token, 'ids' => $ids]);
        $d = json_decode($c, true);

        return $d;
    }

    /**
     *
     * 得到指定ID数组的教师信息
     * @apiName getAllTeachers
     * @apiGroup Comme
     *
     *
     * @apiSuccess {String[]} data 取得的教师信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　  [code] => 1
     * [msg] =>
     * [time] => 1573529107
     * [data] => Array
     * (
     *[0] => Array (
     * [id] => 41 [teacher_name] => 张三 [gender] => 0 [avatar] => /uploads/20191113/2863d0a1ff4b87ba621cb84637c3796d.jpg )
     *
     * )
     * ]
     */
    public function getAllTeachers()
    {


        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/school/teachers", ['access_token' => $this->access_token, 'id' => session('schoolInfo.id')]);
        $d = json_decode($c, true);

        return $d;
    }


    /**
     *
     * 根据姓名或电话得到教师id数组
     * @apiName getTeacherId
     * @apiGroup Comme
     *
     * @apiParam {string} $keywords 电话或姓名
     *
     * @apiSuccess {String[]} data 取得的教师id数组
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　
     * [code] => 1
     * [msg] =>
     * [time] => 1573625425
     * [data] => Array
     * (
     * [0] => 35
     * )
     * ]
     */
    public function getTeacherId($keywords = '')
    {
        if (empty($keywords))
            return ['data'=>[]];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/teacher/search", ['access_token' => $this->access_token, 'keywords' => $keywords]);
        $d = json_decode($c, true);

        return $d;
    }


    /**
     *
     * 得到指定ID数组的学生信息
     * @apiName getStudents
     * @apiGroup Comme
     *
     * @apiParam {string[]} $ids student_id组成的数字数组
     *
     * @apiSuccess {String[]} data 取得的学生信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　 [code] => 1
        [msg] =>
        [time] => 1573635548
        [data] => Array
        (
        [2] => Array
        (
        [id] => 2
     *  [number] => 18414249
        [name] => 谢玲玲
        [avatar] => https://mp.uxuj.cn/uploads/20190927/41568e32086aa8fd576d14ed42d3c37b.jpg
        )

        )
     * ]
     */
    public function getStudents($ids = [])
    {
        if (empty($ids) || !is_array($ids))
            return ['data'=>[]];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/student/profile", ['access_token' => 'suzhiok', 'ids' => $ids]);
        $d = json_decode($c, true);

        return $d;
    }

    /**
     *
     * 得到指定ID数组的班级名，地点等
     * @apiName getClasses
     * @apiGroup Comme
     *
     * @apiParam {string[]} $ids class_id组成的数字数组
     *
     * @apiSuccess {String[]} data 取得的班级信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　 [code] => 1
        [msg] =>
        [time] => 1573635548
        [data] => Array
        (
            [1] => Array
            (
            [id] => 1
            [name] => 三班
            [classroom_name] => 101教室
            [building_name] => 1楼
            )

            [2] => Array
            (
            [id] => 2
            [name] => 十五班
            [classroom_name] => 101教室
            [building_name] => 1楼
            )
        )
     * ]
     */
    public function getClasses($ids = [])
    {
        if (empty($ids) || !is_array($ids))
            return ['data'=>[]];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/location", ['access_token' => $this->access_token, 'ids' => $ids]);
        $d = json_decode($c, true);

        return $d;
    }

    /**
     *
     * 得到指定grade_id的班级
     * @apiName getClassesByGradeIds
     * @apiGroup Comme
     *
     * @apiParam {string[]} $grade_id 年级ID
     *
     * @apiSuccess {String[]} data 取得的班级信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　 [code] => 1
        [msg] =>
        [time] => 1573635548
        [data] => Array
        (
            [0] => Array
            (
            [id] => 4
            [name] => 三班
            [type] => 1
            )

            [1] => Array
            (
            [id] => 2
            [name] => 十五班
            [type] => 1

            )
        )
     * ]
     */
    public function getClassesByGradeIds($grade_id)
    {
        if (empty($grade_id) )
            return [];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/grade/classes", ['access_token' => $this->access_token, 'school_id' => session('schoolInfo.id'), 'grade_id' => $grade_id]);
        $d = json_decode($c, true);

        return $d;
    }

    /**
     *
     * 得到指定ID数组的学科信息
     * @apiName getSubjectsByIds
     * @apiGroup Comme
     *
     * @apiParam {string[]} $ids sub_id组成的数字数组
     *
     * @apiSuccess {String[]} data 取得的班级信息
     *             {int} code 状态码
     * @apiSuccessExample Success-Response:
     * [
     * 　 [code] => 1
    [msg] =>
    [time] => 1573635548
    [data] => Array
    (
        [8] => Array
        (
        [id] => 8
        [name] => 政治
        [type] => 1
        )

        [20] => Array
        (
        [id] => 20
        [name] => 数学
        [type] => 1
        )
    )
     * ]
     */
    public function getSubjectsByIds($ids = [])
    {
        if (empty($ids) || !is_array($ids))
            return ['data'=>[]];

        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/subject/profile", ['access_token' => $this->access_token, 'ids' => $ids]);
        $d = json_decode($c, true);

        return $d;
    }

    //单点登录验证
    public function sso_login()
    {

        $this->soo_broker->attach(true);

        $user = null;
        try {
            $user = $this->soo_broker->getUserInfo();
            // if(empty($user)){
            // 	$user['id'] = 1;
            // 	$user['username'] = "测试数据";
            // }
        } catch (NotAttachedException $e) {
            header('Location: ' . $_SERVER['REQUEST_URI']);
            exit;
        } catch (SsoException $e) {
            $this->error($e->getMessage(), '');
        }
        // p($user);die;
        if ($user) {
            // 有用户信息 先取本地session,等到用户$u
            $u = session('admin');
            if ($u) {
                if ($u['id'] != $user['id']) {
                    //替换新用户session
                    session('admin', $user);
                }
            } else {
                //设置本地session,新的$user进行登录
                session('admin', $user);
            }
        } else {
            //没有登录 清除session,跳转登录页
            session('admin', null);
        }
    }

    //验证是否登录
    public function isLogin()
    {
        $user = session('admin');
        if ($user['id']) {
            $this->assign('user', $user);
            return true;
        }
        return false;
    }

    //语言切换
    public function lang()
    {
        $data = request()->param();
        switch ($data['type']) {
            case 'zh':
                cookie('think_var', 'zh-cn');
                break;
            case 'en':
                cookie('think_var', 'en-us');
                break;
            default:
                cookie('think_var', 'zh-cn');
        }
        return show(1, "设置成功", 0, 200);
    }

    //清除缓存
    public function clearCache()
    {
        $data = request()->param();
        switch ($data['type']) {
            case '1':
                $data = Cache::clear();
                $data = Dir::del('runtime/temp');
                $data = Dir::del('runtime/log');
                break;
            case '2':
                $data = Dir::del('runtime/temp');
                break;
            case '3':
                $data = Cache::clear();
                break;
            default:
                $data = Cache::clear();
        }


        if ($data) {
            return show(1, lang("cache_clear_success"), 0, 200);
        } else {
            return show(0, lang("cache_clear_error"), 0, 200);
        }
    }

    public function outLogin()
    {
        $this->soo_broker->logout();
        session(null);
        $data = Cache::clear();
        $data = Dir::del('runtime/temp');
        $data = Dir::del('runtime/log');
        return show(0, '退出成功', [], 200);
    }

    //获取班级列表
    public function getClass()
    {
        $map = [
            'access_token' => $this->access_token
        ];
        if (session('schoolInfo.id')) {
            $map['school_id'] = session('schoolInfo.id');
        }
        // p($map);die;
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/index", $map);
        // p($c);die;
        $d = json_decode($c, true);
        // p(json_encode($d));die;
        return $d;
    }

    //根据班级id集合拉取选项目
    public function egetClass($class_ids)
    {
        $map = [
            'access_token' => $this->access_token
        ];
        if ($class_ids) {
            $map['class_ids'] = $class_ids;
        }
        if (session('schoolInfo.id')) {
            $map['school_id'] = session('schoolInfo.id');
        }
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/index", $map);
        $d = json_decode($c, true);
        return $d;
    }

    public function getAllRoom()
    {
        $map = [
            'access_token' => $this->access_token
        ];
        if (session('schoolInfo.id')) {
            $map['school_id'] = session('schoolInfo.id');
        }
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classroom", $map);
        $d = json_decode($c, true);
        return $d;
    }

    //获取教室关联信息
    public function getRoomRelation($classroom_ids)
    {
        $map = [
            'access_token' => $this->access_token
        ];
        if ($classroom_ids) {
            $map['classroom_ids'] = $classroom_ids;
        }
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classroom", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

    //给客户端发送多对多信息
    //$param 对应班牌的设备号(注册码)
    //$content 内容
    public function socketPush($class_ids, $content)
    {

        $map['access_token'] =  config('app.access_token');
        $map['content'] = json_encode($content);
        $device_ids = db('device_association')->where('class_id', 'in', $class_ids)->column('device_id');
        if (is_array($device_ids) && count($device_ids, COUNT_NORMAL) > 0) {
            $map['device_ids'] = $device_ids;
            $client = new Client([
                'base_uri' => 'https://mp.uxuj.cn/admin/',
                'timeout' => 30,
                'allow_redirects' => true
            ]);
            $response = $client->request('POST', 'api/socket/publish', [
                'form_params' => $map
            ]);
            $body = $response->getBody();
            $contents = [];
            if ($body->getSize()) {
                $contents = $body->getContents();
            }
            return $contents;
        } else {
            return show(0, "暂无发送客户端", 0, 200);
        }
    }
    //给客户端发送多对多信息
    //$param 对应班牌的设备号(注册码)
    //$content 内容
    public function socketPush_device($device_ids, $content)
    {

        $map['access_token'] =  config('app.access_token');
        $map['content'] = json_encode($content);
        if (is_array($device_ids) && count($device_ids, COUNT_NORMAL) > 0) {
            $map['device_ids'] = $device_ids;
            $client = new Client([
                'base_uri' => 'https://mp.uxuj.cn/admin/',
                'timeout' => 30,
                'allow_redirects' => true
            ]);
            $response = $client->request('POST', 'api/socket/publish', [
                'form_params' => $map
            ]);
            $body = $response->getBody();
            $contents = [];
            if ($body->getSize()) {
                $contents = $body->getContents();
            }
            return $contents;
        } else {
            return show(0, "暂无发送客户端", 0, 200);
        }
    }

    //所有科目

    /*
     *
     *
     * Array
        (
            [0] => Array
                (
                    [id] => 3
                    [name] => 语文
                )

            [1] => Array
                (
                    [id] => 4
                    [name] => 数学
                )

    )*/

    public function allSubject()
    {
        $map = [
            'access_token' => $this->access_token
        ];
        if (session('schoolInfo.id')) {
            $map['school_id'] = session('schoolInfo.id');
        }
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/subject/index", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

    //设备列表
    public function devices($offset, $limit, $keywords)
    {

        $map = [
            'access_token' => $this->access_token
        ];
        if (session('schoolInfo.id')) {
            $map['school_id'] = session('schoolInfo.id');
            $map['page'] = $offset;
            $map['list_rows'] = $limit;
            $map['keywords'] = $keywords;
        }
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/device/index", $map);
        $d = json_decode($c, true);
        // p($d);die;
        return $d['data'];
    }

    //通过id获取当前班级的基本信息
    public function class_info_id($id)
    {
        $map = [
            'access_token' => config('app.access_token'),
            'class_id' => $id
        ];
        // p($map);die;
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/profile", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

    //基础平台重置信息
    public function reset($ids)
    {
        $map = [
            'access_token' => config('app.access_token'),
            'ids' => $ids
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/device/reset", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

    /*
     *
     * Array
(
    [1] => 三班
    [2] => 十五班
)
     * */
    public function getNameById($ids)
    {
        $map = [
            'access_token' => $this->access_token,
            'class_ids' => $ids
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/getNameById", $map);
        $d = json_decode($c, true);
        return $d['data'];

    }

    //修改设备名称
    public function editName($id, $name)
    {
        $map = [
            'access_token' => $this->access_token,
            'id' => $id,
            'name' => $name
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/device/editName", $map);
        $d = json_decode($c, true);
        return $d;

    }
    //统计学校数据 班级数、教师数、家长数、学生数
    public function statistics($id)
    {
        $map = [
            'access_token' => $this->access_token,
            'id' => $id
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/school/statistics", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

    //获取班级课表
    public function get_classes_course($id)
    {
        $map = [
            'access_token' =>config('app.access_token'),
            'class_id' => $id
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/course", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }
    //通过班级id获取班级学生列表
    public function students_list($class_id){
        $map = [
            'access_token' => config('app.access_token'),
            'id' => $class_id
        ];
        $c = (new Curl())->post("https://mp.uxuj.cn/admin/api/classes/students", $map);
        $d = json_decode($c, true);
        return $d['data'];
    }

}
